#include "client.h"
#include <iostream>
#include <thread>

Client::Client(const char *addr, int port) {
    if(WSAStartup(MAKEWORD(2, 2), &wsaData)) {
        WSACleanup();
        throw "ERROR::调用 WSAStartup() 方法发生错误！\n";
    }
    cliSock = socket(AF_INET, SOCK_STREAM, 0);
    cliAddr.sin_family = AF_INET;
    cliAddr.sin_addr.S_un.S_addr = inet_addr(addr);
    cliAddr.sin_port = htons(port);
    if(connect(cliSock, (SOCKADDR*)&cliAddr, sizeof(cliAddr))) {
        WSACleanup();
        closesocket(cliSock);
        throw "ERROR::调用 connect() 方法发生错误！\n";
    }
}

void recvMsg(SOCKET cliSock) {
    char buf[1024] = {0};
    while (true) {
        int nRecv = recv(cliSock, buf, sizeof(buf), 0);
        if(nRecv == SOCKET_ERROR) break;
        std::cout<<buf<<'\n';
    }
}

void Client::monitor() {
    std::thread t(recvMsg, cliSock);
    t.detach();
}

int Client::sendMsg(const char* msg) {
    return send(cliSock, msg, sizeof(msg), 0);
}

Client::~Client() {
    WSACleanup();
    closesocket(cliSock);
}
